본 게시글의 원문은 Yann Debray의 MATLAB with Python Book 입니다. 해당 책은 MIT 라이센스를 따르기 때문에 개인적으로 번역하여 재배포 합니다. 본 포스팅에는 추후 유료 수익을 위한 광고가 부착될 수도 있습니다.

MIT License

Copyright (c) 2023 Yann Debray

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

본 게시물에서 활용된 소스 코드들은 모두 Yann Debray의 GitHub Repo에서 확인할 수 있습니다.

4.1. MATLAB에서 Python 문장 및 파일 실행하기

R2021b부터 pyrun을 사용하여 MATLAB에서 직접 Python 문장을 실행할 수 있습니다. 이렇게 하면 스크립트로 래핑하지 않고도 간단한 Python 코드 조각을 실행할 수 있습니다.

pyrun("l = [1,2,3]")
pyrun("print(l)")
[1, 2, 3]

위와 같이 pyrun 함수는 상태를 유지하며 이전 호출에서 정의된 변수를 유지합니다. Python 변수를 MATLAB 측에서 가져올 때는 두 번째 인수로 변수를 지정하면 됩니다.

pyrun("l2 = [k^2 for k in l]","l2")
ans = 
  Python list with values:

    [3, 0, 1]

    Use string, double or cell function to convert to a MATLAB array.

여기서는 l 변수의 값을 사용하여 l2 변수를 생성하고 해당 값을 출력하였습니다.

로컬 스코프에서 정의된 변수 목록은 dir() 함수를 사용하여 가져올 수 있습니다.

D = pyrun("d = dir()","d")
D = 
  Python list with values:

    ['__builtins__', '__name__', 'l', 'l2']

    Use string, double or cell function to convert to a MATLAB array.

위 코드에서는 현재 스코프에 정의된 변수 목록을 가져와 D 변수에 저장하였습니다.

만약 Python 코드 조각을 스크립트에 붙여넣는 것이 더 편리하다면 pyrunfile 함수를 사용할 수 있습니다.